package org.fatmansoft.teach.controllers.ViewController;

import org.fatmansoft.teach.Repository.ViewRepository.HonorInfo.HonorTypeRepository;
import org.fatmansoft.teach.Repository.ViewRepository.HonorInfo.StudentHonorRepository;
import org.fatmansoft.teach.Repository.ViewRepository.StudentRepository;
import org.fatmansoft.teach.entity.ViewEntity.HonorInfo.HonorType;
import org.fatmansoft.teach.entity.ViewEntity.HonorInfo.StudentHonor;
import org.fatmansoft.teach.entity.ViewEntity.Student;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/honorInfo")
public class StudentHonorController {
    @Autowired
    StudentRepository studentRepository;

    @Autowired
    StudentHonorRepository studentHonorRepository;

    @Autowired
    HonorTypeRepository honorTypeRepository;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @PostMapping("/getInfo")
    public DataResponse getInfo(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        int currentPage = 1;  //分页页码
        String RequestCurPage = Utils.parseRequest(request, "currentPage", map);  //获取解析的数据
        if (RequestCurPage != null & Utils.checkNum(RequestCurPage)) {  //要求数据不为空，且为纯数字
            currentPage = Integer.parseInt(RequestCurPage);
        }

        String studentNum = "";  //学号
        String RequestStuNum = Utils.parseRequest(request, "studentNum", map);  //获取解析的数据
        if (RequestStuNum != null) {  //要求数据不为空
            studentNum = RequestStuNum;
        }

        List<StudentHonor> studentHonorList = null;  //创建学生列表，用于返回前端
        if (!studentNum.equals("")) {  //按照学号查询
            studentHonorList = studentHonorRepository.findStudentHonorByStudentId(Integer.parseInt(studentNum));
        } else {  //不按照学号查询
            studentHonorList = studentHonorRepository.findAll(PageRequest.of(currentPage - 1, 5)).toList();
        }

        List<Student> studentList = studentRepository.findAll().subList(0, studentRepository.findAll().size());

        map.put("tableData", studentHonorList);
        map.put("studentList", studentList);
        map.put("total", studentHonorRepository.findAll().size());

        return new DataResponse("0", map);
    }

    @PostMapping("/deleteInfo")
    public DataResponse delete(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        String deleteId = Utils.parseRequest(request, "deleteId", map);
        if (Utils.checkNum(deleteId)) {
            studentHonorRepository.deleteById(Integer.parseInt(deleteId));
        }

        return new DataResponse("0", map);
    }

    @PostMapping("/updateAndCreateInfo")
    public DataResponse updateAndCreate(@Valid @RequestBody DataRequest request) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        String code;
//        从前端获取formData转化为Map
        Map formData = (Map) request.getData().get("formData");

        StudentHonor studentHonor = new StudentHonor();
        Student theStudent = new Student();  //学生对象

        if (formData.get("id") != null) studentHonor.setId(Integer.parseInt(formData.get("id").toString()));
        else {  //如果没有传入id->查找数据库，补全ID
            int lastRecord = studentHonorRepository.findAll().size() - 1;
            int lastId = studentHonorRepository.findAll().get(lastRecord).getId();
            studentHonor.setId(lastId + 1);
        }
        if (formData.get("studentId") != null) {  //获取学生ID
            theStudent.setId(Integer.parseInt(formData.get("studentId").toString()));
            studentHonor.setStudent(theStudent);
        }

        if (formData.get("honorTypeId") != null) {  //获取荣誉类型的方法
            HonorType honorType = new HonorType();
            if (honorTypeRepository.findById((int) Long.parseLong(formData.get("honorTypeId").toString())).isPresent()) {
                honorType = honorTypeRepository.findById((int) Long.parseLong(formData.get("honorTypeId").toString())).get();
            }
            studentHonor.setHonorType(honorType);
        }
//        if (formData.get("honorType") != null &                studentHonorRepository.findById((int) Long.parseLong(formData.get("honorType").toString())).isPresent()) {
//            honorType = honorTypeRepository.findById((int)Long.parseLong(formData.get("honorType").toString())).get();
//            studentHonor.setHonorType(honorType);
//        }
        if (formData.get("prizeName") != null)
            studentHonor.setPrizeName(formData.get("prizeName").toString());
        if (formData.get("gameName") != null)
            studentHonor.setGameName(formData.get("gameName").toString());
        if (formData.get("prizeDate") != null)
            studentHonor.setPrizeDate(sdf.parse(formData.get("prizeDate").toString() + " 00:00:00"));  //获取活动日期


//        判断当前元组是否已经存在（根据ID是否存在)
        if (studentHonorRepository.findById(studentHonor.getId()).isPresent()) {  //查看id是否已经存在
            code = "0"; //表示更新
        } else {
            code = "1"; //表示新增
        }

        studentHonorRepository.save(studentHonor);  //更新/保存的数据

        return new DataResponse(code, map);
    }
}
